$(function () {
    let [registration,subject]=[undefined,"televisionLiteratureWritten"];
    const subjectList=["broadCasting","aviationService","radioDirectorWritten","radioDirectorInterview","televisionLiteratureWritten","televisionLiteratureInterview"];
    const a=[
        {
            "type" : 2,
            "subjects": [
                {
                    "name":"broadcasting",
                    "chinese":"稿件朗读",
                    "max":100,
                    "min":0
                },
                {
                    "name":"impromptu",
                    "chinese":"即兴评述",
                    "max":100,
                    "min":0
                },
                {
                    "name":"acquirement",
                    "chinese":"才艺展示",
                    "max":100,
                    "min":0
                }
            ]
        },
        {
            "type" : 2,
            "subjects": [
                {
                    "name":"appearance",
                    "chinese":"外表形象",
                    "max":70,
                    "min":0
                },
                {
                    "name":"aviationtalent",
                    "chinese":"才艺展示",
                    "max":30,
                    "min":0
                },
                {
                    "name":"major",
                    "chinese":"专业基础",
                    "max":60,
                    "min":0
                },
                {
                    "name":"culture",
                    "chinese":"文化素养",
                    "max":40,
                    "min":0
                }
            ]
        },
        {
            "type" : 1,
            "subjects": [
                {
                    "name":"television",
                    "chinese":"电视栏目创意及策划",
                    "max":150,
                    "min":0
                }
            ]
        },
        {
            "type" : 2,
            "subjects": [
                {
                    "name":"interview",
                    "chinese":"命题创意",
                    "max":100,
                    "min":0
                },
                {
                    "name":"judge",
                    "chinese":"评委提问",
                    "max":50,
                    "min":0
                }
            ]
        },
        {
            "type" : 1,
            "subjects": [
                {
                    "name":"story",
                    "chinese":"故事编写",
                    "max":80,
                    "min":0
                },
                {
                    "name":"movies",
                    "chinese":"影视评论",
                    "max":120,
                    "min":0
                }
            ]
        },
        {
            "type" : 2,
            "subjects": [
                {
                    "name":"written",
                    "chinese":"面试成绩",
                    "max":100,
                    "min":0
                }
            ]
        }
    ];

    if (gck("k")!==undefined){
        sck("k",gck("k"),30*60*1000);
        sck("u",gck("u"),30*60*1000);
    }

    function sck(k, v, t) {
        let d = new Date();
        d.setTime(d.getTime() + (t));
        let expires = "expires="+ d.toUTCString();
        document.cookie = k + "=" + v + ";" + expires + ";path=/";
    }

    function getNum(n){
        switch (n) {
            case 1 : {n=2;break;}
            case 2 : {n=5;break;}
            default : n=0;
        }
        return n;
    }

    function number(x) {
        return x===""?-1:Number(x);
    }

    function bubbleSort(arr) {
        let nums = arr.length;
        let temp = 0;
        for(let i = 0; i < nums - 1; i++) {
            for(let j = 0; j < nums - 1 - i; j++) {
                if(arr[j] > arr[j + 1]) {
                    temp = arr[j];
                    arr[j] = arr[j+1];
                    arr[j+1] = temp;
                }
            }
        }
        return arr;
    }

    function getAch(type,acheieve) {
        acheieve=bubbleSort(acheieve);
        if (type===2){
            return (acheieve[1]+acheieve[2]+acheieve[3])/3;
        }else {
            return (acheieve[0]+acheieve[1])/2;
        }
    }

    function ach(type,subjects,a){
        let r="";
        for (let i = 0; i < subjects.length; i++) {
            if (i!==0){
                r+=`,`;
            }
            r+=`"${subjects[i].name}":${JSON.stringify(a.slice(i*getNum(type),(i+1)*getNum(type)))}`;
        }
        return `{${r}}`;
    }

    let Base64 = {
        _keyStr: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
        encode: function(e) {
            let t = "";
            let n, r, i, s, o, u, a;
            let f = 0;
            e = Base64._utf8_encode(e);
            while (f < e.length) {
                n = e.charCodeAt(f++);
                r = e.charCodeAt(f++);
                i = e.charCodeAt(f++);
                s = n >> 2;
                o = (n & 3) << 4 | r >> 4;
                u = (r & 15) << 2 | i >> 6;
                a = i & 63;
                if (isNaN(r)) {
                    u = a = 64
                } else if (isNaN(i)) {
                    a = 64
                }
                t = t + this._keyStr.charAt(s) + this._keyStr.charAt(o) + this._keyStr.charAt(u) + this._keyStr.charAt(a)
            }
            return t
        },
        decode: function(e) {
            let t = "";
            let n, r, i;
            let s, o, u, a;
            let f = 0;
            e=e.replace(/[^A-Za-z0-9+/=]/g,"");
            while (f < e.length) {
                s = this._keyStr.indexOf(e.charAt(f++));
                o = this._keyStr.indexOf(e.charAt(f++));
                u = this._keyStr.indexOf(e.charAt(f++));
                a = this._keyStr.indexOf(e.charAt(f++));
                n = s << 2 | o >> 4;
                r = (o & 15) << 4 | u >> 2;
                i = (u & 3) << 6 | a;
                t = t + String.fromCharCode(n);
                if (u !== 64) {
                    t = t + String.fromCharCode(r)
                }
                if (a !== 64) {
                    t = t + String.fromCharCode(i)
                }
            }
            t = Base64._utf8_decode(t);
            return t;
        },
        _utf8_encode: function(e) {
            e = e.replace(/rn/g, "n");
            let t = "";
            for (let n = 0; n < e.length; n++) {
                let r = e.charCodeAt(n);
                if (r < 128) {
                    t += String.fromCharCode(r)
                } else if (r > 127 && r < 2048) {
                    t += String.fromCharCode(r >> 6 | 192);
                    t += String.fromCharCode(r & 63 | 128)
                } else {
                    t += String.fromCharCode(r >> 12 | 224);
                    t += String.fromCharCode(r >> 6 & 63 | 128);
                    t += String.fromCharCode(r & 63 | 128)
                }
            }
            return t
        },
        _utf8_decode: function(e) {
            let t = "";
            let n = 0;
            let r = c1 = c2 = 0;
            while (n < e.length) {
                r = e.charCodeAt(n);
                if (r < 128) {
                    t += String.fromCharCode(r);
                    n++
                } else if (r > 191 && r < 224) {
                    c2 = e.charCodeAt(n + 1);
                    t += String.fromCharCode((r & 31) << 6 | c2 & 63);
                    n += 2
                } else {
                    c2 = e.charCodeAt(n + 1);
                    c3 = e.charCodeAt(n + 2);
                    t += String.fromCharCode((r & 15) << 12 | (c2 & 63) << 6 | c3 & 63);
                    n += 3
                }
            }
            return t
        }
    };

    function gck(k) {
        let name = k + "=";
        let decodedCookie = decodeURIComponent(document.cookie);
        let ca = decodedCookie.split(';');
        for(let i = 0; i <ca.length; i++) {
            let c = ca[i];
            while (c.charAt(0) === ' ') {
                c = c.substring(1);
            }
            if (c.indexOf(name) === 0) {
                return c.substring(name.length, c.length);
            }
        }
        return undefined;
    }

    function num(obj){
        let  regStrs = [
            ['[^\\d\\.]+$', ''], //禁止录入任何非数字和点
            ['\\.(\\d?)\\.+', '.$1'], //禁止录入两个以上的点
            ['^(\\d+\\.\\d{2}).+', '$1'] //禁止录入小数点后两位以上
        ];
        for(let i=0; i<regStrs.length; i++){
            let reg = new RegExp(regStrs[i][0]);
            obj = obj.replace(reg, regStrs[i][1]);
        }
        return obj;
    }

    layui.use(['form', 'layedit', 'laydate'],function () {
        let [from, layer] = [layui.form, layui.layer];
        function logout(){
            if (gck("u")!==undefined){
                $.ajax({
                    url :　`logout?userId=${JSON.parse(Base64.decode(gck("k"))).id}`,
                    type:`get`,
                    dataType:"json"
                });
            }
            sck("k",gck("k"),5*1000);
            sck("u",gck("u"),5*1000);
            setTimeout(function () {
                window.location.href="/index";
            },1000);
        }

        if ([gck("u"),gck("k")].some(i=>i===undefined)){
            layer.msg("未登录，即将进入登录页面");
            logout();
        }

        let t=setTimeout(function () {
            layer.msg("登录状态即将失效,请重新登陆!");
            let t=setInterval(function () {
                layer.msg("登录状态即将失效,请重新登陆!");
            },60*1000);
            clearInterval(t);
            logout();
        },25*60*1000);


        $("html").on("click","#logout",function () {clearTimeout(t);
            logout();
        }).on("click","#user-return-home",function () {
            $("#my_target").attr("src","/welcome");
            setTimeout(function () {
                $("#user-return-home").parent().removeClass("layui-this");
            },500);
        });

        if (gck("s")===undefined){
            layer.msg("error!");
            setTimeout(function () {
                window.location.href="/welcome";
            },1000);
            return;
        }

        let cacheObject = JSON.parse(gck("s"));
        console.log("cacheObject:"+cacheObject);

        let registration = cacheObject.registration;
        let studentSid =cacheObject.studentSid;
        let subject=cacheObject.subjects;

        $("#studentName").val(cacheObject.studentName);
        $("#registration").val(registration);
        let achievements;
        console.log(gck("s"));
        //管理员修改的页面,填写成绩表单
        if (cacheObject.achievements!==undefined){
            achievements=JSON.parse(cacheObject.achievements);
            let achievements2=undefined;
            if(cacheObject.achievements2!==undefined){
                achievements2=JSON.parse(cacheObject.achievements2);
            }
            console.log(achievements2);
            let index= subjectList.findIndex(i=>i===subject);
            let [len,num]=[a[index].subjects.length,getNum(a[index].type)];
            for (let i = 0; i < len; i++) {
                let k=a[index].subjects[i].name;
                for (let j = 0; j < num; j++) {
                    let select;
                    if(a[index].type===1){
                        select=`form input:eq(${i*2+j})`;
                    }else {
                        select=`form input:eq(${i+j*len})`;
                    }
                    if (achievements2!==undefined&&achievements[k][j]!==achievements2[k][j]){
                        $(select).addClass("red");
                    }
                    $(select).val(achievements[k][j]);
                }
            }
            //管理员核对学生成绩
            if (cacheObject.achievements2===undefined){
                $("table input").attr({"disabled":"disabled","readonly": "readonly"});
                $("#submit-achievement").parent().attr("id","menu").find("*").remove();
                $("#menu").html(`<a style="display: inline-block;height: 38px;line-height: 38px;padding: 0 18px;
                background-color: #009688;color: #fff;white-space: nowrap;text-align: center;font-size: 14px;border: none;
                border-radius: 2px;cursor: pointer;margin: 5px;" href="/welcome">返回</a>`);
            }
        }

        //sck("s","",0);
        let bsubmit = true;
        //限制input只能输入两位小数
        $("html").on("keyup","input",function () {
            $(this).val(num($(this).val()));
        }).on("click","#submit-achievement",function () {
            if (gck("k")===undefined){
                layer.msg("登陆状态失效,请重新登陆");
                setTimeout(function () {
                    window.location.href="/index";
                },1000);
                return;
            }
            let index= subjectList.findIndex(i=>i===subject);
            let [formData,oldList,newList,all]=[new FormData,[],[],0];
            if (index===-1){
                layer.msg("error!");
                return;
            }
            for (let i=0;i<$("table input").length;i++){
                oldList.push(number($(`table input:eq(${i})`).val()));
            }
            for (let i = 0; i < a[index].subjects.length; i++) {
                //1.笔试 2.面试
                if (a[index].type===1){
                    //判断笔试成绩是否成绩超过20
                    if (Math.abs(oldList[i*2]-oldList[i*2+1])>=20){
                        layer.msg("笔试成绩差不能超过20");
                        return;
                    }
                    for (let j = 0; j < getNum(a[index].type); j++) {
                        let score=oldList[i*2+j];
                        //判断成绩是否在范围内
                        if (score>a[index].subjects[i].max||score<a[index].subjects[i].min){
                            layer.msg(`成绩有误 位置: ${a[index].subjects[i].chinese} 评委${`${(j+1)}`.replace("1","一").replace("2","二").replace("3","三").replace("4","四").replace("5","五")}`);
                            return;
                        }
                        newList.push(score);
                    }
                    //添加提交单科成绩的表单
                    all+=getAch(a[index].type,oldList.slice(i*2,i*2+2));
                    formData.append(a[index].subjects[i].name,getAch(a[index].type,oldList.slice(i*2,i*2+2)));
                }else {
                    for (let j = 0; j < getNum(a[index].type); j++) {
                        let score=oldList[j*a[index].subjects.length+i];
                        //判断成绩是否在范围内
                        if (score>a[index].subjects[i].max||score<a[index].subjects[i].min){
                            layer.msg(`成绩有误 位置: ${a[index].subjects[i].chinese} 评委${`${(j+1)}`.replace("1","一").replace("2","二").replace("3","三").replace("4","四").replace("5","五")}`);
                            return;
                        }
                        newList.push(score);
                    }
                    //添加提交单科成绩的表单
                    all+=getAch(a[index].type,newList.slice(i*getNum(a[index].type)));
                    formData.append(a[index].subjects[i].name,getAch(a[index].type,newList.slice(i*getNum(a[index].type))));
                }
            }
            formData.append("uid",JSON.parse(Base64.decode(gck("k"))).id);
            formData.append("sid",studentSid);

            formData.append("type",a[index].type);
            formData.append("total",all);
            /*formData.append("uid",1);
            formData.append("sid",1);*/

            //添加提交总成绩的表单
            formData.append("achievements",ach(a[index].type,a[index].subjects,newList));
            if (achievements!==undefined){
                formData.append("admin",true);
            }

            if (bsubmit){
                $.ajax({
                    url:`/submitAchievement`,
                    type:`post`,
                    dataType:`json`,
                    data:formData,
                    processData: false,
                    contentType: false,
                    success:function (msg) {
                        if (msg.ok===1){
                            layer.msg(msg.message);
                            setTimeout(function () {
                                if (achievements===undefined){
                                    window.location.href="/welcome"
                                } else {
                                    window.location.href="/administrator"
                                }
                            },1000);
                            bsubmit = false
                        }else {
                            layer.msg(msg.message);
                        }
                    }
                })
            }else {
                layer.msg("不能重复提交");
            }
        })
    })
});
